package com.voicechat.firstmet.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.TIMManager;
import com.tencent.TIMUserStatusListener;
import com.umeng.analytics.MobclickAgent;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.InviteVoiceChatActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.WsManager;
import com.voicechat.firstmet.imcontrol.BroadcastManager;
import com.voicechat.firstmet.imcontrol.MessageEvent;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.Utils;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Timer;

/**
 * Created by taoyong on 2017/3/13.
 * <p>
 * 初始activity父类
 */
public abstract class BaseActivity extends AppCompatActivity {
    private static final String TAG = "SealAppContext";
    protected Context context;
    protected Activity activity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        activity = this;
        addActivity();
        setContentView(loadLayout());
        //设置竖屏
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        initLayout(savedInstanceState);
    }


    public boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }

    /**
     * 返回状态栏颜色
     *
     * @return 颜色地址
     */
    protected abstract int setStatusBarColor();

    /**
     * 返回状态栏字体是否着色
     *
     * @return true - 黑色<br/> false - 白色
     */
    protected abstract boolean isSettingStatusBarText();

    @Override
    protected void onStart() {
        super.onStart();
        addBroadCrowdedOffline();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
    /**
     * 添加用户掉线监听<br/>
     * 添加用户有网重连监听
     * 添加长链接监听
     */
    private long sendTime = 0L;
    public void addBroadCrowdedOffline() {
        //长链接链接成功之后
        BroadcastManager.getInstance(context).addAction(MessageEvent.WS_HEAD, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(TAG, "onReceive: -----instanceof-----"+(activity instanceof InviteVoiceChatActivity));
            }
        });
        //长链接链接失败
        BroadcastManager.getInstance(context).addAction(MessageEvent.WS_MANAGER, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                MySelfInfoBean.ObjectBean mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                        SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
                //Log.i(TAG, "onReceive: ---------"+(activity instanceof InviteVoiceChatActivity));
                /*if(activity instanceof InviteVoiceChatActivity){
                    activity.finish();
                }*/
                WsManager.getInstance(context).reconnect(mySeleInfo.getId());
            }
        });
        //长链接链接断开
        BroadcastManager.getInstance(context).addAction(MessageEvent.WS_Disconnected, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                MySelfInfoBean.ObjectBean mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                        SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
                Log.i(TAG, "onReceive: ---------"+(activity instanceof InviteVoiceChatActivity));
                if(activity instanceof InviteVoiceChatActivity){
                    activity.finish();
                }
                WsManager.getInstance(context).reconnect(mySeleInfo.getId());
            }
        });
        TIMManager.getInstance().setUserStatusListener(new TIMUserStatusListener() {
            //被踢下线
            @Override
            public void onForceOffline() {
                Log.i(TAG, "onForceOffline: -----");
                Toast.makeText(context, getResources().getString(R.string.forceOffline), Toast.LENGTH_LONG).show();
                Utils.setToken(context);
            }
            @Override
            public void onUserSigExpired() {
                Log.i(TAG, "onUserSigExpired: -----");
            }
        });
    }
   /* private void selectExitLogin() {
        final String token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        String s = SPUtils.getEditoString(SPUtils.SP_MYSELFINFO);
        Parcel parcel = ParcelableUtils.unmarshall(s);
        final MySelfInfo mySelfInfo = MySelfInfo.CREATOR.createFromParcel(parcel);
        Map<String, String> map = Utils.getHashMap();
        map.put("userId", mySelfInfo.getUserId() + "");
        map.put("token", token);
        VolleyRequest.RequestPost(context, HTTPAPI.IS_EXIST_TOKEN, map, new VolleyInterface() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject obj = new JSONObject(response);
                    String result = obj.getString("result");//Looper.prepare();
                    isStartLoginActivity(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyError error) {
                Log.e(TAG, "onError: " + error, error);
                selectExitLogin();
            }
        });
    }
*/
   /* private void selectExit() {
        Log.i(TAG, "selectExit: =======================================");
        final String token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        String s = SPUtils.getEditoString(SPUtils.SP_MYSELFINFO);
        Parcel parcel = ParcelableUtils.unmarshall(s);
        final MySelfInfo mySelfInfo = MySelfInfo.CREATOR.createFromParcel(parcel);
        Map<String, String> map = Utils.getHashMap();
        map.put("userId", mySelfInfo.getUserId() + "");
        map.put("token", token);
        VolleyRequest.RequestPost(context, HTTPAPI.IS_EXIST_TOKEN, map, new VolleyInterface() {
            @Override
            public void onSuccess(String response) {
                Log.d(TAG, "onSuccess: 222222222222222"+response);
                try {
                    JSONObject obj = new JSONObject(response);
                    String result = obj.getString("result");//Looper.prepare();
                    isExit(result, token);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(VolleyError error) {
                Log.e(TAG, "onError: " + error, error);
                selectExit();
            }
        });
    }*/

   /* private void isExit(String result, final String token) {
        if (result.equals("success")) {
            if(activity_imessage instanceof ChatActivity){
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        connect(token);
                    }
                },500);
            }else {
                connect(token);
            }
        } else {
            SPUtils.clearEditorKeyValue();
            Logger.i(TAG,"isExit  LARLoginActivity----");
            Intent io = new Intent(context, LARLoginActivity.class);
            io.putExtra("make", "login");
            startActivity(io);
            PopUtils.hidePopupWindow();
            removeAllActivity();
        }
    }
*/


    /**
     * 加载页面布局
     *
     * @return
     */
    protected abstract int loadLayout();

    /**
     * 初始化布局及其他操作
     *
     * @param savedInstanceState
     */
    protected abstract void initLayout(Bundle savedInstanceState);

    /**
     * 得到控件的方法
     *
     * @param resId 控件的ID
     * @param <T>   控件所属类
     * @return 控件
     */
    protected <T extends View> T findTById(int resId) {
        return (T) findViewById(resId);
    }

    /**
     * 提示框
     *
     * @param value
     */
    protected void toast_MakeText(String value) {
        Toast.makeText(context, value, Toast.LENGTH_SHORT).show();
    }

    private int index = -1;

    public int getIndex() {
        return index;
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index 每个tab页对应的下标。
     */
    protected void setTabSelection(int index) {
        if (this.index == index) {
            return;
        }
        //System.out.println("-------------------------" + this.index);
        // 每次选中之前先清楚掉上次的选中状态
        clearSelection();
        // 开启一个Fragment事务
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        showFragment(transaction, index);
        transaction.commit();
        this.index = index;
    }

    /**
     * 清除掉所有的选中状态。
     */
    protected void clearSelection() {
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    protected void hideFragments(FragmentTransaction transaction) {
    }

    /**
     * 将需要使用的Fragment都置为显示状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    protected void showFragment(FragmentTransaction transaction, int index) {
    }

    /**
     * 添加Activity方法
     */
    protected void addActivity() {
        Log.i(TAG, "addActivity_: ------"+activity);
        App.getInstance().addActivity_(activity);// 调用myApplication的添加Activity方法
    }

    /**
     * 销毁单个Activity方法
     */
    protected void removeActivity() {
        App.getInstance().removeActivity_(activity);// 调用myApplication的销毁单个Activity方法
    }

    /**
     * 销毁所有Activity方法
     */
    protected void removeAllActivity() {
        App.getInstance().removeAllActivity_();// 调用myApplication的销毁所有Activity方法
    }

    @Override
    protected void onDestroy() {
        removeActivity();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //设置竖屏
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        App.getInstance().setRunningActivity(activity);
        MobclickAgent.onResume(this);
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        if (Utils.isServiceRunning(this, "com.voicechat.firstmet.service.FloatVideoWindowService")) {
            Log.i(TAG, "onRestart: -----服务开启---");
        }
        Log.i(TAG, "onRestart: -----------"+isActivityForeground(context,"InviteVoiceChatActivity.class"));
    }
    /**
     *
     * 判断某activity是否处于栈顶
     * @return true在栈顶 false不在栈顶
     */
    private boolean isActivityTop(Class cls,Context context){
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(cls.getName());
    }
    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className   某个界面名称
     *
     */
    public static boolean isActivityForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;
    }

}